﻿using DevExpress.Utils.Menu;
using DevExpress.XtraLayout;
using RedRiver.Framework.XtraCommon.Extensions;
using RedRiver.Framework.XtraCommon.Properties;

namespace RedRiver.Framework.XtraCommon.Templates{
    /// <summary>
    /// 布局控件菜单
    /// </summary>
    public class LayoutControlContextMenu : DXPopupMenu{
        private static LayoutControlContextMenu _instance;
        private LayoutControl _layoutControl;

        private LayoutControlContextMenu(){
            CreateItems();
        }

        public LayoutControlContextMenu(LayoutControl layoutControl) : this(){
            _layoutControl = layoutControl;
        }

        private static LayoutControlContextMenu Instance{
            get{
                if (_instance == null){
                    _instance = new LayoutControlContextMenu();
                }
                return _instance;
            }
        }

        /// <summary>
        /// 创建菜单项
        /// </summary>
        private void CreateItems(){
            Items.Clear();
            Items.BeginUpdate();
            Items.Add(new DXMenuItem("保存默认布局", (s, e) => _layoutControl.SaveDefaultLayout(), Resources.ExportGraphic));
            Items.Add(new DXMenuItem("加载布局文件...", (s, e) => _layoutControl.LoadLayout(), Resources.Save));
            //Items.Add(new DXMenuItem("编辑布局...", OnEditLayout,Resources.));
            Items.BeginUpdate();

            Items.EndUpdate();
        }


        /// <summary>
        /// 附加菜单
        /// </summary>
        /// <param name="layoutControl"></param>
        public static void AttachMenu(LayoutControl layoutControl){
            layoutControl.PopupMenuShowing += LayoutControlShowContextMenu;
            layoutControl.LoadDefaultLayout();
        }

        private static void LayoutControlShowContextMenu(object sender, PopupMenuShowingEventArgs e){
            if ((sender != null) && (sender is LayoutControl) && (e.Menu != null)){
                e.Menu.Items.BeginUpdate();
                DXMenuItemCollection items = e.Menu.Items;
                Instance._layoutControl = (LayoutControl) sender;
                foreach (DXMenuItem item in Instance.Items){
                    items.Add(item);
                }
                e.Menu.Items.EndUpdate();
            }
        }
    }
}